package com.zyc.app.woa;

import android.os.AsyncTask;
import com.zyc.app.woa.data.Gzhcb;
import com.zyc.app.woa.utils.Trace;
import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;

import java.io.IOException;

/**
 * Author: yingchang.zhang
 * Date  : 2014/11/28
 */
public class GetArticlesTotalNumberTask extends AsyncTask<String, Integer, Integer> {
    public static final String TEST_OPEN_ID = "oIWsFt-bJZ55CF_ej85s5QeYTSoM";
    public static final String ACCOUNT_ARTICLES_URL = "http://weixin.sogou.com/gzhjs?cb=sogou.weixin.gzhcb&openid=%s&page=%s&t=%s";
    private String mOpenId = TEST_OPEN_ID;

    @Override
    protected Integer doInBackground(String... params) {
        if (null != params && params.length > 0) {
            mOpenId = params[0];
        }

        String body = null;
        try {
            body = reguestText(mOpenId, 1);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Gzhcb gzhcb = Gzhcb.build(body);
        Trace.log("gzhcb.totalPages : " + (null != gzhcb ? gzhcb.totalPages : 0));
        return null != gzhcb ? gzhcb.totalItems : 0;
    }

    public static String reguestText(String openId, int page) throws IOException {
        String requestUrl = buildAccountArticlesUrl(openId, page);
        Trace.log("requestUrl: " + requestUrl);
        Response response = Jsoup.connect(requestUrl)
                .ignoreContentType(true)
                .followRedirects(true)
//                .data("Content-Type", "application/x-javascript; charset=utf-8")
                .timeout(5000)
                .userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36").execute();
        String body = response.body();
//        String cookie = readLine(body, "document.cookie");
//        Date date = new Date();
//        date.setTime(date.getTime()+5*24*3600*1000);
//        cookie += date.toGMTString();
//        String href = readLine(body, "document.location.href");
//        href = "http://weixin.sogou.com/" + href;
//
//        Trace.log("cookie:" + cookie);
//        Trace.log("href:" + href);
        Trace.log("response:" + body);

        int start = body.indexOf("({");
        int end = body.indexOf("})");
        if (start >= 0 && end >= 0 && end > start) {
            body = body.substring(start + 1, end + 1);
        }

        return body;
    }

    private static String readLine(String content, String lineTag) {
        int index = content.lastIndexOf(lineTag);
        if (index > 0) {
            String destText = content.substring(index);
            String[] texts = destText.split("\"");
            return texts[1];
        }

        return null;
    }

    public static String buildAccountArticlesUrl(String openId, int page) {
        long time = System.currentTimeMillis();
        return String.format(ACCOUNT_ARTICLES_URL, openId, page + "", time);
    }
}
